<?php
declare (strict_types = 1);

namespace app\model\system;

use app\model\BaseModel;
use albert\traits\ModelTrait;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Session;
use think\Model;

/**
 * 系统管理员Model
 * Class SystemAdmin
 * @package app\model\system
 */
class SystemAdmin extends BaseModel
{
    use ModelTrait;

    /**
     * 角色修改器
     * Author: Albert3306
     * Date: 2021/5/7
     * @param $value
     * @return string
     */
    public static function setRolesAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    /**
     * 创建出事账号
     * Author: Albert3306
     * Date: 2020/12/3
     * @return SystemAdmin|Model|bool
     */
    public static function initAccount()
    {
        if (self::initWhere(['username' => 'admin'])->value(('id')) > 0) return true;
        $data = [
            'roles'    => 1,
            'level'    => 0,
            'reg_at'   => date('Y-m-d H:i:s'),
            'reg_ip'   => app('request')->ip(),
            'username' => 'admin',
            'nickname' => '超级管理员',
            'pwd'      => password_hash('dog@2020', PASSWORD_DEFAULT, ['cost' => 11])
        ];
        return self::create($data);
    }

    /**
     * 登录
     * Author: Albert3306
     * Date: 2020/12/3
     * @param $username
     * @param $password
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function login($username, $password): bool
    {
        $adminInfo = self::get(compact('username'));
        if (!$adminInfo) return self::setErrorInfo('登陆的账号不存在!');
        if (!password_verify($password, $adminInfo['pwd'])) return self::setErrorInfo('账号或密码错误，请重新输入');
        if (!$adminInfo['status']) return self::setErrorInfo('账号被禁用或删除!');
        self::setLoginInfo($adminInfo);
        event('SystemAdminLogin', [$adminInfo]);
        return true;
    }

    /**
     * 保存登录信息
     * Author: Albert3306
     * Date: 2020/12/3
     * @param $adminInfo
     */
    public static function setLoginInfo($adminInfo)
    {
        Session::set('aid', $adminInfo['id']);
        Session::set('adminInfo', $adminInfo->toArray());
        Session::save();
    }

    /**
     * 清除登录信息
     * Author: Albert3306
     * Date: 2020/12/4
     */
    public static function clearLoginInfo()
    {
        Session::delete('aid');
        Session::delete('adminInfo');
        Session::save();
    }

    /**
     * 检查用户登陆状态
     * @return bool
     */
    public static function hasActiveAdmin(): bool
    {
        return Session::has('aid') && Session::has('adminInfo');
    }

    /**
     * 获得登陆用户信息
     * @return mixed
     * @throws Exception
     */
    public static function activeAdminInfoOrFail()
    {
        $adminInfo = Session::get('adminInfo');
        if (!$adminInfo) throw new Exception('请登陆');
        if (!$adminInfo['status']) throw new Exception('该账号已被关闭!');
        return $adminInfo;
    }

    /**
     * 获得有效管理员信息
     * @param $id
     * @return array|Model
     * @throws Exception
     */
    public static function getValidAdminInfoOrFail($id)
    {
        $adminInfo = self::get($id);
        if (!$adminInfo) throw new Exception('用户不能存在!');
        if (!$adminInfo['status']) throw new Exception('该账号已被关闭!');
        return $adminInfo;
    }

    /**
     * @return array|null
     * @throws \Exception
     */
    public static function activeAdminAuthOrFail(): ?array
    {
        $adminInfo = self::activeAdminInfoOrFail();
        if (is_object($adminInfo)) $adminInfo = $adminInfo->toArray();
        return $adminInfo['level'] === 0 ? SystemRole::getAllAuth() : SystemRole::rolesByAuth($adminInfo['roles']);
    }

    /**
     * 初始化查询条件
     * Author: Albert3306
     * Date: 2021/5/6
     * @param $where
     * @param null $model
     * @return SystemAdmin|mixed
     */
    public static function initWhere($where, $model = null)
    {
        $model = $model ?? new self;
        if (isset($where['id']) && $where['id'] !== '') {
            $model = $model->where('id', $where['id']);
        }
        if (isset($where['level']) && $where['level'] !== '') {
            $model = $model->where('level', $where['level']);
        }
        if (isset($where['status']) && $where['status'] !== '') {
            $model = $model->where('status', $where['status']);
        }
        if (isset($where['username']) && $where['username'] !== '') {
            $model = $model->where('username', $where['username']);
        }
        if (isset($where['keywords']) && $where['keywords'] !== '') {
            $model = $model->whereLike('id|username|nickname', '%' . $where['keywords'] . '%');
        }
        return $model;
    }

    /**
     * 获取 LayUI 列表数据
     * Author: Albert3306
     * Date: 2021/5/6
     * @param $params
     * @param string $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getLayUIPageList($params, string $field = 'id,username,nickname,roles,reg_ip,reg_at,last_ip,last_at,status'): array
    {
        $model = self::initWhere($params);
        $count = $model->count();
        $data = $model->field($field)->page((int)$params['page'], (int)$params['limit'])->select()->each(function($item) {
            $item['roles'] = SystemRole::initWhere(['ids' => $item->roles])->column('name', 'id');
        })->toArray();
        return compact('count', 'data');
    }

    /**
     * @param string $field
     * @param int $level
     * @return Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOrdAdmin(string $field = 'real_name,id', int $level = 0): Collection
    {
        return self::where('level', '>=', $level)->field($field)->select();
    }
}
